import { getLoginLogs } from '@/services/api/log';
import { getSelect } from '@/services/api/user';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import React, { useEffect, useRef, useState } from 'react';
import routes from '../../../config/routes';

type RoutesType = {
  path: string;
  name?: string;
  routes?: RoutesType[];
};

const LoginLog: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [dictionary, setDictionary] = useState<any>({
    routesObj: {},
    typeName: {
      insert: '新增',
      update: '修改',
      delete: '删除',
      export: '导出',
    },
    typeColor: {
      insert: '',
      update: '#4096ff',
      delete: '#F5222D',
    },
    moduleName: {
      customer: '客户名称',
      supplier: '供应商名称',
      order: '订单编号',
    },
  });

  const initRoutes = (targetObj: any, targetArr: RoutesType[]) => {
    targetArr.forEach((el: any) => {
      const pathName = el.pathName;
      targetObj[pathName] = el.name;

      if (el.routes?.length) {
        initRoutes(targetObj, el.routes);
      }
    });
    return targetObj;
  };

  const initData = () => {
    const dic = dictionary;
    let obj: any = initRoutes({}, routes);
    dic.routesObj = obj;
    setDictionary(dic);
  };
  const columns: ProColumns[] = [
    {
      title: '用户名称',
      key: 'login_user_id',
      dataIndex: 'login_user_id',
      fieldProps: {
        fieldNames: {
          label: 'nickname',
          value: 'id',
        },
        showSearch: true,
      },
      valueType: 'select',
      request: async () => {
        const { data } = await getSelect();
        return data;
      },
    },
    {
      title: '登陆时间',
      key: 'created_time',
      dataIndex: 'created_time',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: 'IP',
      key: 'ip',
      dataIndex: 'ip',
      hideInSearch: true,
      render: (_, record) => {
        return <span style={{ color: '#1890ff' }}>{record.ip}</span>;
      },
    },
  ];

  useEffect(() => {
    initData();
  }, []);
  return (
    <PageContainer>
      <ProTable<API.Logs.AddLog, API.PageParams>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        pagination={{
          showSizeChanger: true,
        }}
        request={getLoginLogs}
        columns={columns}
        rowSelection={false}
        rowClassName={(record) => {
          if (record.type === 'export' || record.type === 'delete') {
            return 'title_bgc';
          }
          return '';
        }}
      />
    </PageContainer>
  );
};

export default LoginLog;
